CC          = arm-none-eabi-gcc
LD          = arm-none-eabi-ld
AR          = arm-none-eabi-ar
OBJCOPY     = arm-none-eabi-objcopy
OBJDUMP     = arm-none-eabi-objdump

TARGET_NAME      = test.bin
TARGET_ELF_NAME  = test.elf
TARGET_DIS_NAME  = test.dis
SYSTEM_LD_NAME   = ld.lds
SYSTEM_MAP_NAME  = system.map

TOP_DIR     = .
OUT_DIR     = $(TOP_DIR)/out
INCLUDEDIR 	:= $(TOP_DIR)/include
ARCH    	:= $(TOP_DIR)/arm920T
BASEDRIVER  := $(TOP_DIR)/basedriver
LIBPRINTF   := $(TOP_DIR)/libprintf
USBSLAVE    := $(TOP_DIR)/usbslave
VIDEO       := $(TOP_DIR)/video
NET         := $(TOP_DIR)/net

TARGET      = $(OUT_DIR)/$(TARGET_NAME)
TARGET_ELF  = $(OUT_DIR)/$(TARGET_ELF_NAME)
TARGET_DIS  = $(OUT_DIR)/$(TARGET_DIS_NAME)
SYSTEM_LD   = $(TOP_DIR)/$(SYSTEM_LD_NAME)
SYSTEM_MAP  = $(OUT_DIR)/$(SYSTEM_MAP_NAME)

CFLAGS 		:= -Wall -O2
INCLUDES   	:= -I$(INCLUDEDIR)
LIBFLAGS    := -lgcc -L/work/all-tools/opt/EmbedSky/arm-2009q1/lib/gcc/arm-none-eabi/4.3.3/

S_FILES_START := $(ARCH)/start.S
S_FILES_START += $(ARCH)/lowlevel_init.S
C_FILES_START := $(ARCH)/nand.c
C_FILES_START += $(ARCH)/interrupts.c
C_FILES_START += $(ARCH)/main.c

C_FILES_START := $(patsubst ./%, %, ${C_FILES_START})
C_OBJS_START  := $(C_FILES_START:%.c=${OUT_DIR}/%.o)
S_FILES_START := $(patsubst ./%, %, ${S_FILES_START})
S_OBJS_START  := $(S_FILES_START:%.S=${OUT_DIR}/%.o)

C_FILES :=
S_FILES :=

include $(BASEDRIVER)/Makefile
include $(LIBPRINTF)/Makefile
include $(USBSLAVE)/Makefile
include $(VIDEO)/Makefile
include $(NET)/Makefile

C_FILES := $(patsubst ./%, %, ${C_FILES})
C_OBJS  := $(C_FILES:%.c=${OUT_DIR}/%.o)
S_FILES := $(patsubst ./%, %, ${S_FILES})
S_OBJS  := $(S_FILES:%.S=${OUT_DIR}/%.o)

OBJS += $(S_OBJS_START) $(C_OBJS_START) $(S_OBJS) $(C_OBJS)

INCLUDES := $(patsubst ./%, %, ${INCLUDES})
INCLUDES := $(patsubst %, -I%, $(patsubst -I%, %, ${INCLUDES}))

$(TARGET): $(OBJS)
	${LD} -static -T$(SYSTEM_LD) -nostdlib -nostartfiles -Map $(SYSTEM_MAP) -o $(TARGET_ELF) $^ --start-group ${LIBFLAGS} --end-group
	${OBJCOPY} -O binary -S $(TARGET_ELF) $@
	${OBJDUMP} -D -m arm $(TARGET_ELF) > $(TARGET_DIS)

$(S_OBJS_START):$(OUT_DIR)/%.o: %.S
	@echo '$(TARGET): ${CC} $<'
	@mkdir -p $(dir $@)
	@${CC} $(INCLUDES) $(CFLAGS) -c $< -o $@

$(C_OBJS_START):$(OUT_DIR)/%.o: %.c
	@echo '$(TARGET): ${CC} $<'
	@mkdir -p $(dir $@)
	@${CC} $(INCLUDES) $(CFLAGS) -c $< -o $@

$(S_OBJS):$(OUT_DIR)/%.o: %.S
	@echo '$(TARGET): ${CC} $<'
	@mkdir -p $(dir $@)
	@${CC} $(INCLUDES) $(CFLAGS) -c $< -o $@

$(C_OBJS):$(OUT_DIR)/%.o :%.c
	@echo '$(TARGET): ${CC} $<'
	@mkdir -p $(dir $@)
	@${CC} $(INCLUDES) $(CFLAGS) -c $< -o $@

.PHONY: clean
clean:
	@rm -rf $(OUT_DIR)
	@echo clean done

.PHONY: debug
debug:
	@echo C_FILES_START = ${C_FILES_START}
	@echo C_OBJS_START  = ${C_OBJS_START}
	@echo S_FILES_START = ${S_FILES_START}
	@echo S_OBJS_START  = ${S_OBJS_START}
	@echo C_FILES = ${C_FILES}
	@echo C_OBJS  = ${C_OBJS}
	@echo S_FILES = ${S_FILES}
	@echo S_OBJS  = ${S_OBJS}
	@echo OBJS    = ${OBJS}
	@echo INCLUDES  = ${INCLUDES}
